36
Beginner’s Guide to Code Algorithms
36
The example above had only 30 of the 81 cells filled in and the objective of the
Sudoku puzzle is to fill them all in.
Getting the correct number to fill in an empty cell can be hard but very addictive
and fulfilling. After this puzzle exploded in popularity in 2005, most newspapers and
magazines feature this puzzle and some grade it according to their level of difficulty.
The popular belief is that the first Sudoku puzzle appeared in Japan in 1984, which
explains its Japanese name. Sudoku is a shortened version of a Japanese expression,
“Suji wa dokushin ni kagiru”, which means the digits are limited to one occurrence.
In this chapter we are going to discuss the art of building algorithms to solve
Sudoku puzzles using a macro.
We are not going to spend a lot of time on developing a nice user interface—you
can do that on your own with the skills you have learnt in Chapter 2. Instead, we are
going to focus on the logic of solving the puzzle and get inspired by the various tech
niques that can be implemented to solve them using a program.
You might be thinking, where is the fun of solving a puzzle like Sudoku if the
program is going to solve it? We will discuss how you can use a combination of com
puter and human efforts to solve such a puzzle, so that the control still remains on
the user on how much of the puzzle the user wants to solve oneself! Perhaps you got
badly stuck with only five numbers to go? Perhaps you just want one more number?
You can do that using code in the program that specifically stops or pauses in order to
allow the user to exercise their brain!
The discussion starts with a simple user interface. Since this is played on a 9 by 9
grid, that is what we will do first.
FIGURE 3.2 9 by 9 matrix.
We have now defined a 9 by 9 matrix as shown in the yellow highlighted area in
our spreadsheet above. Note that I reduced the row and column widths so that they
appear more like the real puzzle squares.
Each cell has an address. Since my cursor is on the first row and first column, the
address being shown here is A1. In the program we will refer to each as Cell(row,
column) where row and column vary from 1 to 9.